package ltd.handler;

import java.io.ByteArrayOutputStream;

import ltd.bean.JacksonMapper;
import ltd.bean.MSGResult;
import ltd.bean.Session;
import ltd.constant.NetProtocolConstant;
import ltd.entity.Game;
import ltd.entity.User;
import ltd.helper.AESHelper;
import ltd.helper.ChannelGroupHelper;
import ltd.helper.RSAHelper;
import ltd.helper.SpringHelper;
import ltd.server.ServerMain;
import ltd.service.GameService;
import ltd.service.UserService;
import ltd.util.NetUtil;
import ltd.util.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.googlecode.genericdao.search.Filter;
import com.googlecode.genericdao.search.Search;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.util.CharsetUtil;

/**
 * 业务逻辑处理类
 */
public class MyControlHandler {
	private static Logger logger = LoggerFactory.getLogger(MyControlHandler.class);
	
	/** 用户服务类 */
	private UserService userSer;
	
	/** 游戏对象服务类 */
	private GameService gameSer;

	private MyControlHandler() {
		super();
		init();
	}
	
	private static class MyControlHolder{
		private static final MyControlHandler INSTANCE = new MyControlHandler();
	}
	
	public static final MyControlHandler getInstance(){
		return MyControlHolder.INSTANCE;
	}

	/** 初始化服务类 */
	private void init() {
		if(userSer == null){
			userSer = (UserService)SpringHelper.getBean("userService");
		}
		if(gameSer == null){
			gameSer = (GameService) SpringHelper.getBean("gameService");
		}
	}
	
	/** 检查游戏ID是否正确 */
	public boolean checkGameServer(int gid){
		Search search = new Search(Game.class);
		search.addFilterEqual("id", gid);
    	return gameSer.count(search) > 0;
	}
	
	/** 连接登录服务器 */
	public void doConnectServer(Channel channel, String msgStr) {
		ObjectMapper mapper = JacksonMapper.getMapper();
		MSGResult msgres = new MSGResult();
		String sendstr = "";
		try {
			//解析数据
			JsonNode root = mapper.readTree(msgStr);
			JsonNode gidstr = root.get("gid");
			int gid = gidstr.asInt();
			if(gid < 1){
				msgres.setData("连接参数错误");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CONNECT_LOGINSERVER_RES);
        		return;
			}
			//检测该游戏ID是否正确
			if(checkGameServer(gid)){
//				Session session = MyChannelGroup.getInstance().getSessionMap().get(channel.id().toString());
				Session session = ChannelGroupHelper.getSession(channel.id().toString());
				session.setLoginGameId(gid);
				//检测该游戏服务器是否连接
//				if(MyChannelGroup.getInstance().getGameMap().get(gid) != null){
				if(ChannelGroupHelper.getGameSession(gid) != null){
			    	msgres.setData("ok");
			    	msgres.setErr(false);
				}else{
					msgres.setData("该游戏当前为关闭状态");
					msgres.setErr(true);
				}
			}else{
				msgres.setData("无此游戏ID");
				msgres.setErr(true);
			}
			sendstr = mapper.writeValueAsString(msgres);
			//System.out.println("要发送的JSON消息内容为：" + sendstr);
			sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CONNECT_LOGINSERVER_RES);
		} catch (Exception e) {
			e.printStackTrace();
			try {
				msgres.setData("连接错误");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, sendstr, NetProtocolConstant.KICK_OUT);
        		channel.close();
			} catch (Exception e2) {
			}
			logger.error("服务端 用户连接 处理出错");
		}
	}
	
	/** 检测名称 */
	public void doCheckName(Channel channel, String msgStr){
		ObjectMapper mapper = JacksonMapper.getMapper();
		MSGResult msgres = new MSGResult();
		String sendstr = "";
		try {
			init();
			//获取Session
//			Session sess = MyChannelGroup.getInstance().getSessionMap().get(channel.id().toString());
			Session sess = ChannelGroupHelper.getSession(channel.id().toString());
			if(sess == null){
        		msgres.setData("错误：Session is null...");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, sendstr, NetProtocolConstant.KICK_OUT);
        		channel.close();
                return;
        	}
			//判断消息内容
			if(msgStr != null && !msgStr.isEmpty()){
				JsonNode root = mapper.readTree(msgStr);
				JsonNode nameNode = root.get("name");
	        	if(nameNode == null){
	        		msgres.setData("无名称信息");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CHECK_NAME_RES);
	        		return;
	        	}
    			String regex2 = "[a-zA-Z0-9_\u4e00-\u9fa5]+$";
    			String name = nameNode.asText().trim();
    			if(name.length() < 2 || name.length() > 10 || !name.matches(regex2)){
	        		msgres.setData("名称由 2-10 个字符的数字、英文或中文组成");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CHECK_NAME_RES);
	        		return;
	    		}
	        	//验证该名称是否已被使用
	        	Search search = new Search(User.class);
				search.addFilterEqual("name", name);
				search.addFilterEqual("gid", sess.getLoginGameId());
				int count = userSer.count(search);
				if(count > 0){
					msgres.setData("1");
				}else{
					msgres.setData("0");
				}
				msgres.setErr(false);
				sendstr = mapper.writeValueAsString(msgres);
	        	sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CHECK_NAME_RES);
			}else{
				msgres.setData("消息内容错误");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CHECK_NAME_RES);
        		return;
			}
		} catch (Exception e) {
			try {
				msgres.setData("检测名称出错");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, sendstr, NetProtocolConstant.CHECK_NAME_RES);
			} catch (Exception e2) {
			}
			logger.error("服务端 检测名称 处理出错");
			e.printStackTrace();
		}
	}
	
	/** 检测SN */
	public void doCheckSN(Channel channel, String msgStr){
		ObjectMapper mapper = JacksonMapper.getMapper();
		MSGResult msgres = new MSGResult();
		String sendstr = "";
		try {
			init();
			//获取Session
//			Session sess = MyChannelGroup.getInstance().getSessionMap().get(channel.id().toString());
			Session sess = ChannelGroupHelper.getSession(channel.id().toString());
			if(sess == null){
        		msgres.setData("错误：Session is null...");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, sendstr, NetProtocolConstant.KICK_OUT);
        		channel.close();
                return;
        	}
			//判断消息内容
			if(msgStr != null && !msgStr.isEmpty()){
				JsonNode root = mapper.readTree(msgStr);
				JsonNode snNode = root.get("sn");
	        	if(snNode == null){
	        		msgres.setData("无数据信息");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CHECK_SN_RES);
	        		return;
	        	}
	        	String sn = null;
				try {
					sn = snNode.asText().trim();
				} catch (Exception e) {
					e.printStackTrace();
					msgres.setData("SN数据解析错误");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CHECK_SN_RES);
					return;
				}
				//验证消息格式
	        	String regex1 = "^[a-zA-Z0-9_]+$";
	        	if(sn.length() < 5 || sn.length() > 100 || !sn.matches(regex1)){
	        		msgres.setData("SN由 5-100 个字符的数字或英文组成");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CHECK_SN_RES);
	        		return;
	        	}
	        	//查询是否有该序列号的用户
	    		Search search = new Search(User.class);
	    		search.addFilterEqual("gid", sess.getLoginGameId());
	    		search.addFilterEqual("sn", sn);
				if(userSer.count(search) > 0){
					msgres.setData("1");
	        		msgres.setErr(false);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CHECK_SN_RES);
				}else{
	        		msgres.setData("0");
	        		msgres.setErr(false);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CHECK_SN_RES);
				}
			}else{
				msgres.setData("消息内容错误");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.CHECK_SN_RES);
        		return;
			}
		} catch (Exception e) {
			try {
				msgres.setData("Session错误");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, sendstr, NetProtocolConstant.KICK_OUT);
        		channel.close();
			} catch (Exception e2) {
			}
			logger.error("服务端 检测SN 处理出错");
			e.printStackTrace();
		}
	}
	
	/** 序列号检测登录 */
	public void USER_SN(Channel channel, String msgStr){
		ObjectMapper mapper = JacksonMapper.getMapper();
		MSGResult msgres = new MSGResult();
		String sendstr = "";
		try {
			init();
			//获取Session
//			Session sess = MyChannelGroup.getInstance().getSessionMap().get(channel.id().toString());
			Session sess = ChannelGroupHelper.getSession(channel.id().toString());
			if(sess == null){
        		msgres.setData("错误：Session is null...");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, sendstr, NetProtocolConstant.KICK_OUT);
        		channel.close();
                return;
        	}
			//获取游戏服务器的Session，判断游戏是否开服
//			Session gameSession = MyChannelGroup.getInstance().getGameMap().get(sess.getLoginGameId());
			Session gameSession = ChannelGroupHelper.getGameSession(sess.getLoginGameId());
			if(gameSession == null){
				msgres.setData("游戏服务器当前为关闭状态");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
			}
			//判断消息内容
			if(msgStr != null && !msgStr.isEmpty()){
				JsonNode root = mapper.readTree(msgStr);
				JsonNode snNode = root.get("sn");
	        	if(snNode == null){
	        		msgres.setData("无登录信息");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
	        		return;
	        	}
	        	String sn = null;
				try {
					sn = snNode.asText().trim();
				} catch (Exception e) {
					e.printStackTrace();
					msgres.setData("登录信息数据解析错误");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
					return;
				}
				//验证消息格式
	        	String regex1 = "^[a-zA-Z0-9_]+$";
	        	if(sn.length() < 5 || sn.length() > 100 || !sn.matches(regex1)){
	        		msgres.setData("序列号由 5-100 个字符的数字或英文组成");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
	        		return;
	        	}
	        	//查询是否有该序列号的用户
	    		Search search = new Search(User.class);
	    		search.addFilterEqual("gid", sess.getLoginGameId());
	    		search.addFilterEqual("sn", sn);
	    		search.setMaxResults(1);
	    		User user = userSer.searchOne(search);
				if(user != null){
					//检查该用户是否被禁用
					if(user.isState()){
						msgres.setData("该用户已被禁用");
		        		msgres.setErr(true);
		        		sendstr = mapper.writeValueAsString(msgres);
		        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
		        		return;
					}
					//处理登录
					doUserLogin(channel, user);
				}else{
					sess.setNu(true);
					//没有则创建
					user = new User();
					try {
		        		if(root.has("name")){
		        			String regex2 = "[a-zA-Z0-9_\u4e00-\u9fa5]+$";
		        			JsonNode nameNode = root.get("name");
		        			String name = nameNode.asText().trim();
		        			if(name.length() < 2 || name.length() > 10 || !name.matches(regex2)){
		    	        		msgres.setData("名称由 2-10 个字符的数字、英文或中文组成");
		    	        		msgres.setErr(true);
		    	        		sendstr = mapper.writeValueAsString(msgres);
		    	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
		    	        		return;
		    	    		}
		    	        	//验证该名称是否已被使用
		    	    		search.clear();
		    				search.addFilterEqual("name", name);
		    				search.addFilterEqual("gid", sess.getLoginGameId());
		    				int count = userSer.count(search);
		    				if(count > 0){
		    					msgres.setData("该名称已被注册");
		    	        		msgres.setErr(true);
		    	        		sendstr = mapper.writeValueAsString(msgres);
		    	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
		    	                return;
		    				}
		    				user.setName(name);
		        		}
					} catch (Exception e) {
						msgres.setData("名称格式错误");
		        		msgres.setErr(true);
		        		sendstr = mapper.writeValueAsString(msgres);
		        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
		                return;
					}
					user.setSn(sn);
					user.setGid(sess.getLoginGameId());
					user.setState(false);
					user.setType(false);
					autoUserReg(channel, user, true);
				}
			}else{
				msgres.setData("消息内容错误");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
        		return;
			}
		} catch (Exception e) {
			try {
				msgres.setData("登录错误");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, sendstr, NetProtocolConstant.KICK_OUT);
        		channel.close();
			} catch (Exception e2) {
			}
			logger.error("服务端 用户SN登录 处理出错");
			e.printStackTrace();
		}
	}
	
	/** 用户注册 */
	public void USER_REG(Channel channel, String msgStr){
		ObjectMapper mapper = JacksonMapper.getMapper();
		MSGResult msgres = new MSGResult();
		String sendstr = "";
		try {
			init();
			//获取用户Session
//			Session sess = MyChannelGroup.getInstance().getSessionMap().get(channel.id().toString());
			Session sess = ChannelGroupHelper.getSession(channel.id().toString());
			if(sess == null){
        		msgres.setData("错误：Session is null...");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, sendstr, NetProtocolConstant.KICK_OUT);
        		channel.close();
                return;
        	}
			//获取该游戏的Session
//			Session gameSession = MyChannelGroup.getInstance().getGameMap().get(sess.getLoginGameId());
			Session gameSession = ChannelGroupHelper.getGameSession(sess.getLoginGameId());
			if(gameSession == null){
				msgres.setData("游戏服务器当前为关闭状态");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_REG_RES);
			}
			//判断消息内容
			if(msgStr != null && !msgStr.isEmpty()){
				JsonNode root = mapper.readTree(msgStr);
				JsonNode unNode = root.get("username");
	        	JsonNode pwNode = root.get("password");
	        	JsonNode naNode = root.get("name");
	        	if(unNode == null || pwNode == null || naNode == null){
	        		msgres.setData("请将注册信息填写完整");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_REG_RES);
	        		return;
	        	}
	        	//验证消息格式
	        	String regex1 = "^[a-zA-Z0-9_]+$";
	    		String regex2 = "[a-zA-Z0-9_\u4e00-\u9fa5]+$";
	    		String username = unNode.asText().trim();
				String password = pwNode.asText().trim();
				String name = naNode.asText().trim();
				if(username.length() < 4 || username.length() > 20 || !username.matches(regex1)){
	        		msgres.setData("用户名由 4-20 个字符的数字或英文组成");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_REG_RES);
	        		return;
	        	}
	        	if(password.length() < 4 || password.length() > 20 || !password.matches(regex1)){
	        		msgres.setData("密码由 4-20 个字符的数字或英文组成");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_REG_RES);
	        		return;
	        	}
	        	if(name.length() < 2 || name.length() > 10 || !name.matches(regex2)){
	        		msgres.setData("名称由 2-10 个字符的数字、英文或中文组成");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_REG_RES);
	        		return;
	    		}
	        	//验证该用户名是否已被使用
	    		Search search = new Search(User.class);
	    		search.addFilterEqual("username", username);
	    		search.addFilterEqual("gid", sess.getLoginGameId());
	    		int count = userSer.count(search);
				if(count > 0){
					msgres.setData("该用户名已被注册");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_REG_RES);
	                return;
				}
				//验证该名称是否被使用
				search.clear();
				search.addFilterEqual("name", name);
				search.addFilterEqual("gid", sess.getLoginGameId());
				count = userSer.count(search);
				if(count > 0){
					msgres.setData("该名称已被注册");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_REG_RES);
	                return;
				}
				//创建新用户
				User user = new User();
				user.setUsername(username);
				user.setPassword(password);
				user.setName(name);
				user.setGid(sess.getLoginGameId());
				user.setState(false);
				user.setType(false);
				int num = 0;
				String cname;
				//创建查询器
	    		Search searchSN = new Search(User.class);
				do {
					cname = RandomUtil.getCname() ;
					searchSN.addFilterEqual("sn", "sn" + cname);
					searchSN.addFilterEqual("gid", user.getGid());
					num = userSer.count(searchSN);
					searchSN.clear();
				} while (num > 0);
				user.setSn("sn" + cname);
				doUserRegedit(channel, user);
			}else{
				//消息内容错误
				msgres.setData("消息内容错误");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_REG_RES);
        		return;
			}
		} catch (Exception e) {
			try {
				msgres.setData("注册错误");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, sendstr, NetProtocolConstant.KICK_OUT);
        		channel.close();
			} catch (Exception e2) {
			}
			logger.error("服务端 用户登录 处理出错");
			e.printStackTrace();
		}
	}
	
	/** 用户登录，默认是否自动创建用户 */
	public void USER_LOGIN(Channel channel, String msgStr){
		this.USER_LOGIN(channel, msgStr, ServerMain.AUTO_REG);
	}
	
	/** 用户登录，定义是否自动创建 */
	public void USER_LOGIN(Channel channel, String msgStr, boolean isAutoReg){
		ObjectMapper mapper = JacksonMapper.getMapper();
		MSGResult msgres = new MSGResult();
		String sendstr = "";
		try {
			init();
			//获取用户Session
//			Session sess = MyChannelGroup.getInstance().getSessionMap().get(channel.id().toString());
			Session sess = ChannelGroupHelper.getSession(channel.id().toString());
			if(sess == null){
        		msgres.setData("错误：Session is null...");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, sendstr, NetProtocolConstant.KICK_OUT);
        		channel.close();
                return;
        	}
			//获取游戏服务器Session
//			Session gameSession = MyChannelGroup.getInstance().getGameMap().get(sess.getLoginGameId());
			Session gameSession = ChannelGroupHelper.getGameSession(sess.getLoginGameId());
			if(gameSession == null){
				msgres.setData("游戏服务器当前为关闭状态");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
			}
			//判断消息内容
			if(msgStr != null && !msgStr.isEmpty()){
				JsonNode root = mapper.readTree(msgStr);
				JsonNode unNode = root.get("username");
	        	JsonNode pwNode = root.get("password");
	        	if(unNode == null || pwNode == null){
	        		msgres.setData("请将登录信息填写完整");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
	        		return;
	        	}
	        	String username;
				String password;
				try {
					username = unNode.asText().trim();
					password = pwNode.asText().trim();
				} catch (Exception e) {
					e.printStackTrace();
					msgres.setData("登录信息数据解析错误");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
					return;
				}
				//验证消息格式
	        	String regex1 = "^[a-zA-Z0-9_]+$";
	        	if(username.length() < 4 || username.length() > 20 || !username.matches(regex1)){
	        		msgres.setData("用户名由 4-20 个字符的数字或英文组成");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
	        		return;
	        	}
	        	if(password.length() < 4 || password.length() > 20 || !password.matches(regex1)){
	        		msgres.setData("密码由 4-20 个字符的数字或英文组成");
	        		msgres.setErr(true);
	        		sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
	        		return;
	        	}
	    		Search search = new Search(User.class);
	    		search.addFilterEqual("username", username);
	    		search.addFilterEqual("gid", sess.getLoginGameId());
	    		search.setMaxResults(1);
	    		User user = userSer.searchOne(search);
				if(user != null){
					if(user.getPassword().equals(password)){
						//检查该用户是否被禁用
						if(user.isState()){
							msgres.setData("该用户已被禁用");
			        		msgres.setErr(true);
			        		sendstr = mapper.writeValueAsString(msgres);
			        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
			        		return;
						}
						//处理登录
						doUserLogin(channel, user);
					}else{
						msgres.setData("用户密码错误");
		        		msgres.setErr(true);
		        		sendstr = mapper.writeValueAsString(msgres);
		        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
		        		return;
					}
				}else{
					//是否自动注册
					if(isAutoReg){
						user = new User();
						user.setUsername(username);
						user.setPassword(password);
						user.setGid(sess.getLoginGameId());
						user.setState(false);
						user.setType(false);
						autoUserReg(channel, user, false);
					}else{
						//用户未找到
						msgres.setData("无此用户");
		        		msgres.setErr(true);
		        		sendstr = mapper.writeValueAsString(msgres);
		        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
		        		return;
					}
				}
			}else{
				msgres.setData("消息内容错误");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
        		return;
			}
		} catch (Exception e) {
			try {
				msgres.setData("登录错误");
        		msgres.setErr(true);
        		sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, sendstr, NetProtocolConstant.KICK_OUT);
        		channel.close();
			} catch (Exception e2) {
			}
			logger.error("服务端 用户登录 处理出错");
			e.printStackTrace();
		}
	}
	
	/**
	 * 自动注册用户处理
	 * @param channel session 会话
	 * @param user 注册用户对象
	 * @param type 注册方式：true 自动生成用户名、密码信息，false 根据所传User对象
	 */
	private void autoUserReg(Channel channel, User user, boolean type){
		try {
			boolean isSN = false;
			if(user.getSn() == null || user.getSn().isEmpty()){
				isSN = true;
			}
			int count = 0;
			String cname;
			//创建查询器
    		Search search = new Search(User.class);
			do {
				cname = RandomUtil.getCname() ;
				//是否生成用户名、密码
				if(type){
					if(!isSN){
						if(user.getName() == null || user.getName().isEmpty()){
							search.addFilterOr(
								Filter.or(
									Filter.equal("name", cname),
									Filter.equal("username", cname)
								)
							);
						}else{
							search.addFilterOr(
								Filter.or(
									Filter.equal("name", user.getName()),
									Filter.equal("username", cname)
								)
							);
						}
					}else{
						search.addFilterOr(
							Filter.or(
								Filter.equal("name", cname),
								Filter.equal("username", cname),
								Filter.equal("sn", "sn" + cname)
							)
						);
					}
				}else{
					if(!isSN){
						if(user.getName() == null || user.getName().isEmpty()){
							search.addFilterEqual("name", cname);
						}else{
							search.addFilterEqual("name", user.getName());
						}
					}else{
						search.addFilterOr(
							Filter.or(
								Filter.equal("name", cname),
								Filter.equal("sn", "sn" + cname)
							)
						);
					}
				}
				search.addFilterEqual("gid", user.getGid());
				count = userSer.count(search);
				search.clear();
			} while (count > 0);
			//是否生成用户名、密码
			if(type){
				user.setUsername(cname);
				user.setPassword("123456");
			}
			if(user.getName() == null || user.getName().isEmpty()){
				user.setName(cname);
			}
			if(isSN){
				user.setSn("sn" + cname);
			}
			//进行注册
			doUserRegedit(channel, user);
		} catch (Exception e) {
			//用户注册出错
			logger.error("服务端 用户注册 处理出错");
			e.printStackTrace();
		}
	}
	
	/**
	 * 登录处理
	 * @param channel session 会话
	 * @param user 登录用户对象
	 */
	private void doUserLogin(Channel channel, User user){
		try {
			ObjectMapper mapper = JacksonMapper.getMapper();
			MSGResult msgres = new MSGResult();
			try {
				user.setLastdate("");
				userSer.save(user);
			} catch (Exception e) {
				logger.info("用户：{} 更新登录状态出错!", user.getUsername());
				e.printStackTrace();
			}
			//保存用户信息
//			Session session = MyChannelGroup.getInstance().getSessionMap().get(channel.id().toString());
			Session session = ChannelGroupHelper.getSession(channel.id().toString());
			session.setUser(user);
			logger.info("用户：{} 登录成功!", user.getUsername());
			ObjectNode root1 = mapper.createObjectNode();
			//获取游戏服务器Seesion
//			Session gameSession = MyChannelGroup.getInstance().getGameMap().get(session.getLoginGameId());
			Session gameSession = ChannelGroupHelper.getGameSession(session.getLoginGameId());
			if(gameSession != null){
		    	root1.put("sessionid", session.getSessionId());
		    	root1.put("uid", user.getId());
		    	root1.put("name", user.getName());
		    	root1.put("chid", session.getChannel().id().toString());
		    	String sendstr = root1.toString();
				System.out.println("登录成功的JSON消息内容为：" + sendstr);
				//下发消息
				sendMsg(gameSession.getChannel(), sendstr, NetProtocolConstant.SERVER_USER_LOGIN);
		    	
				/*root1.removeAll();
				
				String userdata = mapper.writeValueAsString(user);
		    	root1.put("userdata", userdata); 
		    	root1.put("iphost", gameSession.getIpAddress().getAddress().getHostAddress());
		    	root1.put("port", gameSession.getPort());
		    	RSAPublicKey gamekey = gameSession.getClientKey();
		    	root1.put("gamemodulus", gamekey.getModulus().toString());
		    	root1.put("gameexponent", gamekey.getPublicExponent().toString());
		    	root1.put("sessionid", session.getSessionId());
		    	sendstr = root1.toString();
		    	msgres.setData(sendstr);
		    	msgres.setErr(false);
		    	String msgresstr = mapper.writeValueAsString(msgres);
				System.out.println("登录成功的JSON消息内容为：" + msgresstr);
				
				sendMsg(channel, RSAHelper.doRSAEncoder(key, msgresstr), NetProtocol.DO_LOGIN_RES);*/
			}else{
				msgres.setData("游戏服务器当前为关闭状态");
        		msgres.setErr(true);
        		String sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_LOGIN_RES);
			}
		} catch (Exception e) {
			//用户登录出错
			logger.error("服务端 用户登录 处理出错");
			e.printStackTrace();
		}
	}
	
	/**
	 * 用户注册处理
	 * @param channel session 会话
	 * @param user 注册用户对象
	 */
	private void doUserRegedit(Channel channel, User user){
		try {
			ObjectMapper mapper = JacksonMapper.getMapper();
			MSGResult msgres = new MSGResult();
//			Session session = MyChannelGroup.getInstance().getSessionMap().get(channel.id().toString());
			Session session = ChannelGroupHelper.getSession(channel.id().toString());
			//保存用户
			if(userSer.save(user)){
				//下发注册后的用户信息数据
				//保存用户信息
				session.setUser(user);
				logger.info("用户：{} 登录成功!", user.getUsername());
				ObjectNode root1 = mapper.createObjectNode();
				//获取游戏服务器Session
//				Session gameSession = MyChannelGroup.getInstance().getGameMap().get(session.getLoginGameId());
				Session gameSession = ChannelGroupHelper.getGameSession(session.getLoginGameId());
				if(gameSession != null){
			    	root1.put("sessionid", session.getSessionId());
					root1.put("name", user.getName());
					root1.put("uid", user.getId());
					root1.put("chid", session.getChannel().id().toString());
			    	String sendstr = root1.toString();
					System.out.println("注册成功的JSON消息内容为：" + sendstr);
					sendMsg(gameSession.getChannel(), sendstr, NetProtocolConstant.SERVER_USER_LOGIN);
			    	
					/*root1.removeAll();
					
					String userdata = mapper.writeValueAsString(user);
			    	root1.put("userdata", userdata); 
			    	root1.put("iphost", gameSession.getIpAddress().getAddress().getHostAddress());
			    	root1.put("port", gameSession.getPort());
			    	RSAPublicKey gamekey = gameSession.getClientKey();
			    	root1.put("gamemodulus", gamekey.getModulus().toString());
			    	root1.put("gameexponent", gamekey.getPublicExponent().toString());
			    	root1.put("sessionid", session.getSessionId());
			    	sendstr = root1.toString();
			    	msgres.setData(sendstr);
			    	msgres.setErr(false);
			    	String msgresstr = mapper.writeValueAsString(msgres);
					System.out.println("注册成功的JSON消息内容为：" + msgresstr);
					
					sendMsg(channel, RSAHelper.doRSAEncoder(key, msgresstr), NetProtocol.DO_REG_RES);*/
				}else{
					msgres.setData("游戏服务器当前为关闭状态");
	        		msgres.setErr(true);
	        		String sendstr = mapper.writeValueAsString(msgres);
	        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_REG_RES);
				}
			}else{
				//用户注册失败
				msgres.setData("用户注册失败");
        		msgres.setErr(true);
        		String sendstr = mapper.writeValueAsString(msgres);
        		sendMsg(channel, RSAHelper.doRSAEncoderPri(sendstr), NetProtocolConstant.DO_REG_RES);
			}
		} catch (Exception e) {
			//用户注册出错
			logger.error("服务端 用户注册 处理出错");
			e.printStackTrace();
		}
	}
	
	/** 下发登录结果 */
	public void do_LOGIN_RES(Channel channel, String chid){
		if(chid == null || chid.isEmpty()){
			return;
		}
		try {
			ObjectMapper mapper = JacksonMapper.getMapper();
			//获取用户Seesion
//			Session session = MyChannelGroup.getInstance().getSessionMap().get(chid);
			Session session = ChannelGroupHelper.getSession(chid);
			if (session != null) {
				//获取游戏服务器Session
//				Session gameSession = MyChannelGroup.getInstance().getGameMap().get(session.getLoginGameId());
				Session gameSession = ChannelGroupHelper.getGameSession(session.getLoginGameId());
				if (gameSession != null) {
					//封装消息体
					MSGResult msgres = new MSGResult();
					ObjectNode root1 = mapper.createObjectNode();
					root1.put("iphost", gameSession.getIphost());
					root1.put("port", gameSession.getPort());
					root1.put("sessionid", session.getSessionId());
					root1.put("nu", session.isNu());
					root1.put("k", AESHelper.initKeyStr(session.getSessionId()).trim());
					String sendstr = root1.toString();
					msgres.setData(sendstr);
					msgres.setErr(false);
					String msgresstr = mapper.writeValueAsString(msgres);
					System.out.println("注册成功的JSON消息内容为：" + msgresstr);
					//下发消息
					sendMsg(session.getChannel(), RSAHelper.doRSAEncoderPri(msgresstr), NetProtocolConstant.DO_LOGIN_RES);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("...游戏服务器回执后，进行用户数据下发操作出错...");
		}
	}
	
	/**
	 * 发送数据
	 * @param channel 通道对象
	 * @param msgStr 要发送的数据字符串
	 * @param protocol 协议号
	 */
	public void sendMsg(Channel channel, String msgStr, int protocol){
        this.sendMsg(channel, msgStr.getBytes(CharsetUtil.UTF_8), protocol);
	}
	
	/**
	 * 发送数据
	 * @param channel 通道对象
	 * @param msgbytes 要发送的数据字节数组
	 * @param protocol 协议号
	 */
	public void sendMsg(Channel channel, byte[] msgbytes, int protocol){
        try {
        	if(channel != null && channel.isActive()){
				ByteArrayOutputStream bos = new ByteArrayOutputStream(msgbytes.length + 8);
	
				bos.write(NetUtil.intToByteArray(msgbytes.length + 4));
				bos.write(NetUtil.intToByteArray(protocol));
//        		bos.write(TypeChangeUtil.intToByteArray(0));//备用字段
				bos.write(msgbytes);
				
				ByteBuf resp = Unpooled.copiedBuffer(bos.toByteArray());
				channel.writeAndFlush(resp);
        	}
		} catch (Exception e) {
			System.err.println("### 数据发送失败！！！");
			e.printStackTrace();
		}
	}

}
